import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,Input, DatePicker, Button, Card,Icon,Row,Col,message,Modal,Upload
} from 'antd';
import styles from './style.less';
import moment from 'moment';
import SpreadList from '../live/SpreadList';
import docCookies from "../../../common/DocCookies";

const FormItem = Form.Item;

@connect(state => ({
  contentManager: state.contentManager,
}))
@Form.create()
export default class AdAdd extends PureComponent {
  state = {
    id:-1,
    rsId:docCookies.getItem("rsId"),
    userId:docCookies.getItem("userId"),
    pageNo:1,
    pageSize:5,
    total:0,
    resultBtnTxt:"",
    resultContentId:-1,
    modalVisible:false,
    formLoading:false,
    spreadListData:[],

    spreadStarttime: '',
    spreadEndtime: '',
    spreadUrl:'',

    isDisabled:false,
    defaultUploadFileList:[],

    imageUpdateStatus:"",
    imageUpdateFile:null,
    imageUrl:"",
    audioStatus:"paused",

    showDetail:false,
  };

  ////初始化渲染后触发 整个过程只调用一次
  componentDidMount() {
    const { form , dispatch} = this.props;

    if(this.props.location.query) {
      var spreadId = this.props.location.query.spreadId;
      var showDetail = this.props.location.query.showDetail;
      if (spreadId) {
        if(showDetail){
          this.setState({
            showDetail:showDetail
          });
        }
        const params = {
          spreadId: spreadId
        };
        dispatch({
          type: 'contentManager/fetchGetSpreadById',  //请求的action
          payload: params,
          callback: (res) => {
            form.setFields({
              sellerName: {value: res.sellerName},
              spreadTitle: {value: res.spreadTitle},
              spreadExpire: {value: [moment(res.startTime), moment(res.endTime)]},
            })

            this.setState({
              resultBtnTxt: res.activityTitle,
              resultContentId:res.contentId,
              spreadStarttime:moment(res.startTime).format('YYYY/MM/DD h:mm:ss'),
              spreadEndtime:moment(res.endTime).format('YYYY/MM/DD h:mm:ss'),
              rsId:res.rsId,
              id:spreadId
            });
            if( res.resPath != null){
              this.setState({
                imageUpdateStatus: "done",
                imageUpdateFile: {
                  name: res.fileName,
                  url: res.resPath
                },
                imageUrl: res.resPath,
              });

              this.setState({
                isDisabled: true,
              })
            }
          }
        });
      }
    }
  }

  play() {
    var audioAd = this.refs.audio;
    if(this.state.imageUpdateStatus === "done"){
      if (audioAd.paused) {
        this.setState({
          audioStatus:"play"
        });
        audioAd.play();
      } else {
        this.setState({
          audioStatus:"paused"
        });
        audioAd.pause();
      }
    }else if(this.state.imageUpdateStatus === "failed") {
      alert("文件上传失败，无法播放！")
    } else {
      alert("文件正在上传，请稍后重试！")
    }

  }
  delImage(){
    this.setState({
      imageUpdateStatus:"",
      spreadUrl:"",
      imageUpdateFile:null,
      audioStatus:"paused",
    });
    this.refs.audio.pause();
  }
  handleSubmit = () => {
    const { form ,dispatch} = this.props;
    const { spreadStarttime ,spreadEndtime,resultContentId,rsId,id,spreadUrl} = this.state;

    this.setState({
      formLoading: true
    })

    var me= this;
    if(spreadUrl===null||spreadUrl==""){
      me.setState({
        formLoading: false
      });
      alert("请上传音频文件！")
    }else{
      form.validateFields(
        (err, values) => {
          if (!err) {
            values.spreadExpireStart = spreadStarttime;
            values.spreadExpireEnd = spreadEndtime;
            delete values.spreadExpire;
            values.resultContentId = resultContentId;
            values.spreadUrl = spreadUrl;
            values.rsId = rsId;
            values.spreadType = 0;
            if(this.state.id != -1) values.id = id;
            dispatch({
              type: 'contentManager/fetchSaveOrUpdateSpread',  //请求的action
              payload:values,
              callback:(res) =>{
                me.setState({
                  formLoading: false
                });
                message.success(res.msg);
                setTimeout(this.cancelBack(),200);
              }
            });
          }else{
            me.setState({
              formLoading: false
            });
          }
        }
      );
    }

  }

  cancelBack = () => {
    history.go(-1);
  }

  openSelectModel = () => {
    this.setState({
      modalVisible: true,
      loadMethod: this.loadMethod(this.state.pageNo,this.state.pageSize)
    });
  }

  addSpread = (record,index) => {
    this.state.spreadListData.splice(index,1);
    this.setState({
      resultBtnTxt: record.title,
      resultContentId:record.id,
      spreadListData:this.state.spreadListData.concat([])
    });
    this.closeSpreadModal();
  }

  closeSpreadModal = () => {
    this.setState({
      modalVisible: false
    });
  }

  spreadListChange = (page, pageSize) => {
    this.setState({
      pageNo:page,
      pageSize:pageSize
    });

    this.loadMethod(page,pageSize)
  }

  loadMethod(pageNo,pageSize,searchText){
    const { dispatch } = this.props;
    const params = {
      rsId:this.state.rsId,
      pageNo: pageNo,
      pageSize: pageSize
    };
    if(searchText) params.searchText = searchText;

    if(this.state.id != -1) params.spreadId = this.state.id;
    dispatch({
      type: 'contentManager/fetchListSpreadResult',  //请求的action
      payload:params,
      callback:(res) =>{
        this.setState({
          spreadListData: res.list,
          total:res.total
        });
      }
    });
  }

  handleSearch = (value) => {
    const {pageNo,pageSize} = this.state;
    this.loadMethod(pageNo,pageSize,value)
  }

  onDataPickChange = (dates, dateStrings) => {
    this.setState({
      spreadStarttime: dateStrings[0],
      spreadEndtime: dateStrings[1]
    })
  }

  handleFileListChange = (info) =>{
    let file = info.file;
    if(this.state.imageUpdateStatus!==file.status&&file.status === "uploading"){
      //开始上传时停止播放
      var audioAd = this.refs.audio;
        this.setState({
          audioStatus:"paused"
        });
        audioAd.pause();
      this.setState({
        imageUpdateStatus:"uploading",
      });
    }else if(file.status === "done"){
      message.success(file.response.msg);
      if(file.response.errorCode === 1){
        this.setState({
          imageUpdateStatus:"done",
          spreadUrl:file.response.data.upUrl,
          imageUrl:"http://test22umake.oss-cn-beijing.aliyuncs.com/"+file.response.data.upUrl,
          isDisabled:true
        });
      }else{
        this.setState({
          imageUpdateStatus:"failed",
        });
        alert("文件上传失败，请检查网络并重新上传！")
      }

    }
  }

  beforeUpload = file => {
    var fileName = file.name;
    var suffix = fileName.substr(fileName.lastIndexOf('.')+1);

    if(suffix.toLowerCase().endsWith("mp3") || suffix.toLowerCase().endsWith("aac")
      || suffix.toLowerCase().endsWith("wav")){
      this.setState({
        imageUpdateFile:file
      });
      return true;
    }else{
      return false;
    }
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const {resultBtnTxt, total, pageNo, pageSize, spreadListData, modalVisible, isDisabled, formLoading, imageUrl, showDetail, userId, imageUpdateStatus,imageUpdateFile,audioStatus} = this.state;
    const RangePicker = DatePicker.RangePicker;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    const props = {
      name: 'file',
      action: '/api/oss/fileUpload',
      data:{userId:userId,filePath:'test/photo/'},
      accept:'audio/*',
      disabled:isDisabled,
      onChange: this.handleFileListChange ,
      beforeUpload: this.beforeUpload,
    };

    return (

      <div>
        <Form
          hideRequiredMark
          style={{ marginTop: 8 }}
        >
          <Card title="基本信息">
            <FormItem {...formItemLayout} label="商户名称">
              {getFieldDecorator('sellerName', {
                rules: [{
                  required: true,
                  message: '请输入商户名称',
                }]
              })(
                <Input placeholder="商户名称" disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="广告标题">
              {getFieldDecorator('spreadTitle', {
                rules: [{
                  required: true,
                  message: '请输入广告标题',
                }]
              })(
                <Input placeholder="广告标题" disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="广告音频">
              {
                showDetail?null:

                  <Upload {...props}  disabled={showDetail} showUploadList={false}>
                  <Button>
                    <Icon type="upload"/> 上传音频
                  </Button>
                </Upload>
              }

              {imageUpdateStatus!==""?
                <Row style={{marginTop: 8,backgroundColor: "#74cbff"}}>
                  <Col span={3}>
                    {imageUpdateStatus === "uploading"?<Icon type="loading" style={{fontSize: 20, marginLeft: 10, marginRight: 14}}/>
                      :imageUpdateStatus === "failed"?<Icon type="exclamation" style={{fontSize: 20, marginLeft: 10, marginRight: 14,color: "red"}}/>
                        :<Icon type="link" style={{fontSize: 20, marginLeft: 10, marginRight: 14}}/>
                    }
                  </Col>
                    <Col span={!showDetail?15:18}>{imageUpdateFile.name}</Col>
                  <Col span={!showDetail?4:3} onClick={() => this.play()}>
                    {audioStatus==="play"?<Icon type="pause" style={{fontSize: 18,}}/>
                      :<Icon type="caret-right" style={{fontSize: 18,}}/>}

                  </Col>
                  <Col span={!showDetail?2:0} onClick={() => this.delImage()}>
                    <Icon type="close" style={{fontSize: 18, marginRight: 14}}/>
                  </Col>
                </Row>:null
              }

            </FormItem>
            <FormItem {...formItemLayout} label="结果页面" >
                <Button  style={{width:'100%'}} onClick={()=>this.openSelectModel()} disabled={showDetail}>{resultBtnTxt}</Button>
            </FormItem>
            <FormItem {...formItemLayout} label="摇一摇有效期">
              {getFieldDecorator('spreadExpire', {
                rules: [{
                  required: true,
                  message: '请选择有效期',
                }],
              })(
                <RangePicker
                  disabled={showDetail}
                  ranges={{ "今天": [moment(), moment()], '这个月': [moment(), moment().endOf('month')] }}
                  showTime
                  format="YYYY/MM/DD HH:mm:ss"
                  onChange={this.onDataPickChange}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Card>
          <FormItem {...formItemLayout}  >
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 20 }}>
            <Row gutter={16} style={{ marginBottom: '10px' }}>
              <Col className="gutter-row" span={9}>
              </Col>
              <Col className="gutter-row" span={3}>
                <Button type="primary" htmlType="submit" loading={formLoading}
                        onClick={() => this.handleSubmit()} disabled={showDetail} >保存</Button>
              </Col>
              <Col className="gutter-row" span={3}>
                <Button onClick={() => this.cancelBack()}>取消</Button>
              </Col>
              <Col className="gutter-row" span={9}>
              </Col>
            </Row>
          </FormItem>
          <Modal
            title="增加结果页面"
            visible={modalVisible}
            footer={null}
            onCancel={() => this.closeSpreadModal()}
          >
            <SpreadList
              spreadListData={spreadListData}
              onChange={this.spreadListChange}
              handleSearch={this.handleSearch}
              total = {total}
              pageNo = {pageNo}
              pageSize = {pageSize}
              addSpread = {this.addSpread}
            />
          </Modal>
        </Form><audio ref="audio"
                                       style={{display: "none"}}
                                       src={imageUrl}
                                       preload={"auto"}
        > 您当前的浏览器不支持该播放控件
        </audio>

      </div>
    );
  }
}
